﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;

namespace SMS.UploadAPI.App_Start.Attributes
{
    public class JobApiAttribute : Attribute, IActionFilter
    {
        private readonly string secret;

        public JobApiAttribute()
        {
            var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("Config/appsettings.json").Build();
            secret = configuration.GetSection("HttpJob:JobSecret").Value;
        }

        public void OnActionExecuted(ActionExecutedContext context)
        {
        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            try
            {
                string headerSecret = context.HttpContext.Request.Headers["job_secret"];
                if (headerSecret != null && headerSecret.Equals(secret))
                {
                    return;
                }
                else
                {
                    context.Result = new StatusCodeResult((int)HttpStatusCode.Unauthorized);
                }
            }
            catch
            {
                context.Result = new StatusCodeResult((int)HttpStatusCode.Unauthorized);
            }
        }
    }
}
